package com.zdb.demo.java.leetcode.q3longestsubstringwithoutrepeatingcharacters;

import java.util.HashSet;
import java.util.Set;

public class Solution1 {

    public static void main(String[] args) {
        String s = "abcdaceb";
//        System.out.println(lengthOfLongestSubstring(s));
        System.out.println(lengthOfLongestSubstring2(s));
    }

    public static int lengthOfLongestSubstring2(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }


    public static int lengthOfLongestSubstring(String s) {

        // key为字符， value为key所在s中的位置
        Set<Character> set = new HashSet<>();
        int beginIndex = 0;

        int maxLength = 0;
        for(int i=0; i<s.length(); i++) {
            Character c = s.charAt(i);

            if(!set.contains(c)) {
                set.add(c);
            } else {
                maxLength = maxLength < set.size() ? set.size() : maxLength;
                // 如果set中存在，将beginIndex 一位一位的移动到 c对应位置的后一位，并将set里的值移除

                boolean find = false;
                while(!find) {
                    Character tc = s.charAt(beginIndex);
                    if (tc.equals(c)) {
                        find = true;
                    }
                    beginIndex++;
                    set.remove(tc);
                }
                set.add(c);
            }

        }

        maxLength = maxLength < set.size() ? set.size() : maxLength;

        return maxLength;
    }
}
